﻿CREATE PROCEDURE [dbo].[CashRegistersInsert]
(
	@Name varchar(50),
	@KKMNumber varchar(20),
	@NextDocNumber int,
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50)
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @intNextId int
	SET NOCOUNT ON

IF (@Name Is Null) OR (@KKMNumber Is Null) OR (@NextDocNumber Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF (ltrim(@Name) = '') OR (ltrim(@KKMNumber) = '')
BEGIN
	SELECT @intErrCode = 2, @strMsg = 'Незаполнено наименование или номер!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Common', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
INSERT INTO [CD].[CashRegisters] ( Id, [Name], [KKMNumber], NextDocNumber, [Note], [MD], [MW]) 
VALUES (@intNextId, @Name, @KKMNumber, @NextDocNumber, @Note, @MD, @MW);
	
SELECT Id, DepartmentId, Name, KKMNumber, NextDocNumber, Note, MD, MW 
FROM CD.CashRegisters WHERE (Id = @intNextId)
RETURN 0
